//
//  T3FMapPlatformView+T3FMapViewDelegate.swift
//  t3_map
//
//  Created by Cunhai Li on 2024/10/31.
//

import Foundation
import CoreLocation

extension T3FMapPlatformView: T3FMapViewDelegate {

    func mapViewDidFinishLoadingMap(_ mapView: any T3FMapView) {
        channel.invokeMethod("map#didFinishLoadingMap", arguments: nil)
    }
    
    func mapInitComplete() {
        channel.invokeMethod("map#initComplete", arguments: nil)
    }

    func userLocationDidUpdated(location: T3FMapLocation) {

        let json = location.toJson()

        if let jsonString = try? T3FJsonUtil.toString(json) {
            channel.invokeMethod("location#changed", arguments: jsonString)
        }
    }

    func mapView(_ mapView: any T3FMapView, regionWillChangeAnimated animated: Bool, wasUserAction: Bool) {

        let arguments = [
            "animated": animated,
            "wasUserAction": wasUserAction
        ]
        channel.invokeMethod("map#regionWillChange", arguments: try? T3FJsonUtil.toString(arguments))
    }

    func mapViewRegionChanged(_ mapView: any T3FMapView, centerCoordinate: CLLocationCoordinate2D, zoomLevel: CGFloat) {

        let coordinate = ["longitude": centerCoordinate.longitude,"latitude": centerCoordinate.latitude]
        let arguments = [
            "coordinate": coordinate,
            "zoomLevel": zoomLevel
        ] as [String : Any]
        channel.invokeMethod("map#regionChanged", arguments: try? T3FJsonUtil.toString(arguments))
    }

    func mapView(_ mapView: any T3FMapView, regionDidChangeAnimated animated: Bool, wasUserAction: Bool) {
        let arguments = [
            "animated": animated,
            "wasUserAction": wasUserAction
        ]
        channel.invokeMethod("map#regionDidChange", arguments: try? T3FJsonUtil.toString(arguments))
    }
    
    func mapView(_ mapView: any T3FMapView, didTapPolyline routeID: String) {
        channel.invokeMethod("map#didTapPolyline", arguments: routeID)
    }

    func mapView(_ mapView: any T3FMapView, didAnnotationViewTapped annotationOptions: T3FAnnotationOptions) {

        let arguments = [
            "identifier": annotationOptions.identifier,
        ]
        channel.invokeMethod("map#didTapAnnotation", arguments: try? T3FJsonUtil.toString(arguments))
    }
}
